package com.qingmeng.apiinterface;

import com.google.gson.Gson;
import com.qingmeng.apiclientsdk.entry.MonthDay;
import com.qingmeng.apicommon.model.Day.VO.DayHistoryVo;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/day")
public class DayController {


    @Resource
    private Gson gson;

    @PostMapping("/history")
    public String getDayHistory(@RequestBody MonthDay monthDay) {
        String month = monthDay.getMonth();
        String  day = monthDay.getDay();

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();

        Request request = new Request.Builder()
                .url("https://hot.cigh.cn/calendar/date?month=" + month + "&day=" + day)
                .get() // 使用.get()方法更简洁
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String responseBody = response.body().string();
                DayHistoryVo dayHistoryVo = gson.fromJson(responseBody, DayHistoryVo.class);
                if (dayHistoryVo.getCode() == 200){
                    // 定义一个正则表达式模式来匹配特殊字符
                    Pattern pattern = Pattern.compile("[\\r\\n\\t]");

                    // 提取并拼接 year 和 title，同时去除特殊字符
                    return Arrays.stream(dayHistoryVo.getData())
                            .map(data -> {
                                String cleanedYear = pattern.matcher(data.getYear()).replaceAll("");
                                String cleanedTitle = pattern.matcher(data.getTitle()).replaceAll("");
                                return cleanedYear + "年:" + cleanedTitle;
                            })
                            .collect(Collectors.joining(";"));
//                    return dayHistoryVo.toString();
                }else {
                    return "当前接口调用失败，请联系管理员！！！";
                }
            } else {
                throw new RuntimeException("Request failed with code: " + response.code());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
